package com.lg.controller;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lg.pojo.FastDFSFile;
import com.lg.pojo.Result;
import com.lg.util.FastDFSClient;

@RestController
public class FileUploadController {

	
	@PostMapping("/upload")
	public Result uploadFile(@RequestParam("file") MultipartFile file) {
		try {
			String path = save(file);
			return Result.build().setBody(path).setCode("200").setIsSucess(true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
		}
		return Result.build().setBody("").setIsSucess(false).setCode("502");
	}
  
	
	/**
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public String save(MultipartFile file) throws IOException {
		// 文件名
		String filename = file.getOriginalFilename();
		// 文件扩展名
		String ext = filename.substring(filename.lastIndexOf("."));
		InputStream inputStream = file.getInputStream();
		if (inputStream != null) {
			int available = inputStream.available();
			byte[] content = new byte[available];
			inputStream.read(content);
			inputStream.close();
			FastDFSFile fastDFSFile = new FastDFSFile(filename, content, ext);
			String[] upload = FastDFSClient.upload(fastDFSFile);
			String path = FastDFSClient.getTrackerUrl()+upload[0]+"/"+upload[1];
			return path;
		}
		return "";
	}
}
